<?php
// +----------------------------------------------------------------------
// | 文章分类控制器
// +----------------------------------------------------------------------
// | Author: Eric <ieyangxiaoguo@126.com>
// +----------------------------------------------------------------------
// | Copyright ©2017 http://www.zzuyxg.top All rights reserved.
// +----------------------------------------------------------------------
// | 2017年10月10日
// +----------------------------------------------------------------------
namespace app\tdadmin\controller;

use app\common\controller\AdminBaseController;
use app\common\model\CategoryModel;
use think\Db;
use think\Validate;

class CategoryController extends AdminBaseController
{
    /**
     * 文章分类列表
     */
    public function index()
    {
        return $this->fetch();
    }

    /**
     * 分类列表--数据表格数据接口
     * @author Eric ieyangxiaoguo@126.com
     * @param int $trashed 默认0，过滤已删除的分类；所有分类
     * @return mixed
     * @throws \think\Exception\DbException
     */
    public function apiGetCategorys($trashed=0)
    {
        if ($trashed) {
            $categorys = CategoryModel::withTrashed()->withCount('Articles')
            ->order('path asc,list_order desc')
            ->all();
        }else{
            $categorys = CategoryModel::withCount('Articles')->order('path asc,list_order desc')
            ->all();
        }

        foreach ($categorys as $key => $term) {
            $count = substr_count($term['path'], '-');
            $categorys[$key]['tab'] = str_repeat('——', $count-1);
        }

        $res['code'] = 0;
        $res['msg'] = '';
        $res['data'] = $categorys;

        return $res;
    }

    /**
     * 添加分类
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $data = $this->request->param();

            $rules =   [
                'name'  => 'unique:Category,name',
            ];

            $messages  =   [
                'name.unique' => '分类名已存在',
            ];

            $validate = new Validate($rules,$messages);

            if ($validate->check($data)){
                $res['code'] = 1;
                $res['msg'] = '添加成功！';
                $model = new CategoryModel();
                $result = $model->addCategory($data);
                if ($result === false) {
                    $res['code'] = 0;
                    $res['msg'] = '添加失败！';
                }
                addLog("添加了新闻分类",Db::getLastSql());

                return $res;
            }else{
                $res['code'] = 0;
                $res['msg'] = $validate->getError();
                return $res;
            }
        } else {
            $categories = $this->apiGetCategorys(1);
            $this->assign('categories', $categories['data']);
            return $this->fetch();
        }
    }

    /**
     * 编辑分类
     */
    public function edit()
    {
        if ($this->request->isPost()) {
            $data = $this->request->param();
            if (intval($data['id']) === intval($data['parent_id'])){
                $res['code'] = 0;
                $res['msg'] = '上级分类不能是自身！';
                return $res;
            }

            $rules =   [
                'name'  => 'unique:Category,name',
            ];

            $messages  =   [
                'name.unique' => '分类名已存在',
            ];

            $validate = new Validate($rules,$messages);

            if ($validate->check($data)){
                $res['code'] = 1;
                $res['msg'] = '保存成功！';
                $model = new CategoryModel();
                $result = $model->editCategory($data);
                if ($result === false) {
                    $res['code'] = 0;
                    $res['msg'] = '保存失败！';
                }
                addLog("编辑了新闻分类ID:".$data['id'],Db::getLastSql());

                return $res;
            }else{
                $res['code'] = 0;
                $res['msg'] = $validate->getError();
                return $res;
            }
        } else {
            $id = $this->request->param('id', 0, 'intval');
            if ($id > 0) {
                $category = CategoryModel::withTrashed()->get($id)->toArray();

                $categories = $this->apiGetCategorys(1);

                $category['categories'] = $categories['data'];

                $this->assign($category);
                return $this->fetch();
            } else {
                $res['code'] = 0;
                $res['msg'] = '你从哪里来？';
                return $res;
            }
        }
    }

    //检测分类是否重复
    public function checkName()
    {
        $name = $this->request->param('name');

        $data['code'] = 1;
        $data['msg'] = '该名称可用！';

        if (CategoryModel::where('name',$name)->get()) {
            $data['code'] = 0;
            $data['msg'] = '该分类已存在';
        }

        return $data;
    }

    /**
     * 显示/开启操作
     *
     * @author Eric ieyangxiaoguo@126.com
     *         @date 2017年11月26日
     */
    public function doSwitch()
    {
        return parent::switchOperate(new CategoryModel());
    }

    /**
     * 更新字段
     */
    public function updateField()
    {
        return parent::fieldUpdate(new CategoryModel());
    }

    /**
     * 删除文章分类
     */
    public function delete()
    {
        $id = $this->request->param('id');
        $real = $this->request->param('real');
        if ($id) {
            $findCategory = CategoryModel::withTrashed()->get($id);

            if ($real) {
                $result = $findCategory->delete(true);
                $msg = '彻底删除';
            }else{
                $result = $findCategory->delete();
                $msg = '删除';
            }
            addLog("删除了新闻分类：".$findCategory['name'],Db::getLastSql());

            if ($result) {
                $data['code'] = 1;
                $data['msg'] = $msg.'成功！';
            } else {
                $data['code'] = 0;
                $data['msg'] = $msg.'失败！';
            }
        }else {
            $data['code'] = 0;
            $data['msg'] = '你从哪里来？';
        }

        return $data;
    }

    /**
     * 恢复分类
     */
    public function restore()
    {
        $id = $this->request->param('id');
        if ($id) {
            $categoryModel = new CategoryModel();
            // 获取删除的内容
            $findCategory = $categoryModel->onlyTrashed()->get($id);
            $result = $findCategory->restore();

            if ($result) {
                $data['code'] = 1;
                $data['msg'] = '恢复成功！';
            } else {
                $data['code'] = 0;
                $data['msg'] = '恢复失败！';
            }
        }else {
            $data['code'] = 0;
            $data['msg'] = '你从哪里开？';
        }

        return $data;
    }

}
